package io.renren.modules.oss.cloud;

import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import io.renren.modules.oss.config.CloudStorageConfig;
import io.renren.modules.oss.dto.UploadResultDTO;
import io.renren.modules.oss.util.MinioUtil;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @Author huan.xu
 * @Date 2022/11/2 16:26
 * @Description minio存储
 */
public class MinioCloudStorageService extends AbstractCloudStorageService {

  public MinioCloudStorageService(CloudStorageConfig config) {
    this.config = config;
  }

  /**
   * 文件上传
   *
   * @param data 文件字节数组
   * @param path 文件路径，包含文件名
   * @return 返回http地址
   */
  @Override
  public UploadResultDTO upload(byte[] data, String path) {
    return upload(new ByteArrayInputStream(data), path);
  }

  /**
   * 文件上传
   *
   * @param data 文件字节数组
   * @param suffix 后缀
   * @return 返回http地址
   */
  @Override
  public UploadResultDTO uploadSuffix(byte[] data, String suffix) {
    return upload(data, getPath("", suffix));
  }

  /**
   * 文件上传
   *
   * @param inputStream 字节流
   * @param path 文件路径，包含文件名
   * @return 返回http地址
   */
  @Override
  public UploadResultDTO upload(InputStream inputStream, String path) {
    int index1 = path.lastIndexOf("/");
    String fullFileName = path.substring(index1 + 1);
    String filePath = path.substring(0, index1);

    if (!filePath.startsWith("/")) {
      filePath = "/" + filePath;
    }
    String fullFilePath = filePath + "/" + fullFileName;

    try {
      MinioUtil.putObject(fullFilePath, inputStream);
    } catch (Exception e) {
      throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
    }

    return handleDownloadUrl(new UploadResultDTO("", fullFilePath));
  }

  /**
   * 文件上传
   *
   * @param inputStream 字节流
   * @param suffix 后缀
   * @return 返回http地址
   */
  @Override
  public UploadResultDTO uploadSuffix(InputStream inputStream, String suffix) {
    return upload(inputStream, getPath("", suffix));
  }

  /**
   * 组装下载路径
   */
  @Override
  public UploadResultDTO handleDownloadUrl(UploadResultDTO uploadResultDTO) {
    uploadResultDTO.setDownloadUrl(
        config.getMinioDownloadUrl() + "?storagePath=" + uploadResultDTO.getStoragePath());
    return uploadResultDTO;
  }
}
